package sim.ring.tower;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import org.apache.log4j.Logger;

import sim.ring.technical.data.DatabaseConnection;

public class TowerQueryBuilder {
	private static Logger log = Logger.getLogger("sim.ring.tower");
	public static void saveTower(Tower tower) {
		DatabaseConnection db = new DatabaseConnection();
		try {
			db.connectToDB("RingingSimDB");
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Vector<Object> params = new Vector<Object>();
		String sql = "";
		int id = tower.getId();
		
		if (id>0) {
			sql = "UPDATE towers SET "
					+"name=?,"
					+"town=?,"
					+"num_bells=?,"
					+"bell_key=? "
					+ "WHERE id=?";
			
			params.add(tower.getName());
			params.add(tower.getTown());
			params.add(new Integer(tower.getNumBells()));
			params.add(tower.getKey());
			params.add(new Integer(tower.getId()));
		} else {
			sql = "INSERT INTO towers ("
					+"name,"
					+"town,"
					+"num_bells,"
					+"bell_key) "
					+"VALUES ("
					+"?,"
					+"?,"
					+"?,"
					+"?"
					+")";
			
			params.add(tower.getName());
			params.add(tower.getTown());
			params.add(new Integer(tower.getNumBells()));
			params.add(tower.getKey());
		}
		
		try {
			int key = db.issueNonQueryStatement(sql, params);
			if (id==-1) {
				id=key;
				tower.setId(id);
			}
		} catch (SQLException e) {
			//TODO
			log.error(e.getMessage());
		}
		for(Bell bell : tower.getBells())
			BellQueryBuilder.saveBell(bell);
		log.info("Tower " + tower.getName() + " saved with id " + id);
		db.closeDB();
	}
	
	public static Tower loadTower(int id) {
		String name="";
		String town="";
		int numBells=0;
		String key="";
		
		DatabaseConnection db = new DatabaseConnection();
		try {
			db.connectToDB("RingingSimDB");
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String sql = "SELECT * FROM towers " 
					+ "WHERE id=?";
		
		Vector<Object> params = new Vector<Object>();
		params.add(new Integer(id));
		
		ResultSet rs;
		try {
			rs = db.issueQueryStatement(sql, params);
			rs.next();
			id=rs.getInt(1);
			name=rs.getString(2);
			town=rs.getString(3);
			numBells=rs.getInt(4);
			key=rs.getString(5);
		} catch (SQLException e) {
			//TODO
			log.error(e.getMessage());
		} finally {
		//TODO: close everything		
		}
		db.closeDB();
		return new Tower(id, name, town, numBells, key);
	}
}
